#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Predesys Server - Services - Radar
@version: 0.2.5
@license: GPL 3.0 (see "license" file)
@author: Jose A. Jimenez
@contact: jajimc@gmail.com"""

import sys
sys.dont_write_bytecode = True
import os
import os.path
DIR = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(os.path.join(DIR, "../errorlog"))
import errorlog
sys.path.append(os.path.join(DIR, "../core"))
import time
import addresslog
import services

### SERVICE TEMPLATE ###    
def run(userId, args):
    """Runs service.
    @param userId: Current user
    @type userId: C{str}
    @param args: Service input arguments
    @type args: C{list}
    @return: String that can contain messages to send to some devices
    @rtype: C{str}"""
    if userId == None or (type(userId) != str and type(userId) != unicode) or userId == "":
        raise coreexceptions.ValueNotValidException("'userId' must be a not null and not empty string")
    if args == None or type(args) != list:
        raise Exception("'args' must be a string list")
    
    result = ""
    addresslog.update_log_addresses(args, userId)
    
    # Automatic user services trigger
    autoUserServices = services.get_enabled_services_by_type("automatic-user")
    
    for serviceId in autoUserServices:
        try:
            serviceResult = services.run_automatic_service(serviceId, args)
            if serviceResult != None:
                result += serviceResult
        except Exception as exc:
            errorlog.log_exception(exc.args[0], "predesys-server.services.radar.run")
            
    return result
